package cn.itrip.auth.service;

import cn.itrip.auth.exception.DatabaseException;
import cn.itrip.beans.pojo.ItripUser;
import cn.itrip.common.EmptyUtils;
import cn.itrip.common.MD5;
import cn.itrip.common.RedisAPI;
import cn.itrip.dao.itripUser.ItripUserMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.security.auth.login.LoginException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("userService")
public class UserServiceImpl implements UserService {
    @Resource
    private ItripUserMapper itripUserMapper;
    @Resource
    private MailService mailService;
    @Resource
    private SmsService smsService;
    @Resource
    private RedisAPI redisAPI;

    @Override
    public ItripUser checkLogin(String userCode, String password) throws LoginException, DatabaseException {
        Map params =  new HashMap();
        params.put("userCode",userCode);
        params.put("userPassword", MD5.getMd5(password,32));
        List<ItripUser> result = null;
        try {
            result = itripUserMapper.getItripUserListByMap(params);
        } catch (Exception e) {
            e.printStackTrace();
            throw new DatabaseException("数据库异常",e);
        }
        if (EmptyUtils.isEmpty(result)) {
            return null;
        }else{
            ItripUser user = result.get(0);
            if (user.getActivated()==0){
                //未激活
                throw new LoginException("账户未激活");
            }
            return user;
        }
    }

    /**
     * 根据用户名查找用户
     * @param userCode
     * @return
     * @throws Exception
     */
    public ItripUser findByUserCode(String userCode) throws Exception{
        Map<String,Object> param = new HashMap<String, Object>();
        param.put("userCode",userCode);
        List<ItripUser> list = itripUserMapper.getItripUserListByMap(param);
        if (list.size()>0)
            return list.get(0);
        else
            return null;
    }

    @Override
    public void itriptxCreateUser(ItripUser user) throws Exception {
        //1.添加用户信息
        itripUserMapper.insertItripUser(user);
        //2.生成激活码
        String activationCode = MD5.getMd5(new Date().toLocaleString(),32);
        //3.发送邮件
        mailService.sendActivationMail(user.getUserCode(),activationCode);
        //4.激活码存入Redis
        redisAPI.set("activation:"+user.getUserCode(),30*60,activationCode);
    }

    //邮箱验证、激活
    @Override
    public boolean activate(String mail, String code) throws Exception {
        //1.验证激活码
        String value = redisAPI.get("activation:"+mail);
        if(value.equals(code)){
            Map<String,Object> param = new HashMap<String,Object>();
            param.put("userCode", mail);
            List<ItripUser> users = itripUserMapper.getItripUserListByMap(param);
            if(users.size()>0){
                //2.更新用户
                ItripUser user = users.get(0);
                user.setActivated(1);
                user.setUserType(0);//自注册用户
                user.setFlatID(user.getId());
                itripUserMapper.updateItripUser(user);
                return true;
            }
        }else{
            return false;
        }
        return false;
    }

    public void itriptxCreateUserByPhone(ItripUser user) throws Exception{
        //1.创建用户
        itripUserMapper.insertItripUser(user);
        //2.生成验证码（1111-9999）
        int activationCode = MD5.getRandomCode();
        //3.发送验证码
        smsService.send(user.getUserCode(),"1",new String[]{String.valueOf(activationCode),"1"});//发送内容是一个字符串数组，1为有限期分钟
        //4.保存验证码到Redis
        redisAPI.set("activation:"+user.getUserCode(),60,String.valueOf(activationCode));
    }

    @Override
    public void itriptxUpdateUser(ItripUser user) throws Exception {
        itripUserMapper.updateItripUser(user);
    }


    //短信验证
    public boolean validatePhone(String phoneNum,String code) throws Exception{
        //1.比对验证码
        String key = "activation:" + phoneNum;//redis存着的userCode
        String value = redisAPI.get(key);//redis取到的验证码
        if(null!=value&&value.equals(code)){
            ItripUser user = this.findByUserCode(phoneNum);
            if(user!=null) {
                //2.更新用户激活状态
                user.setActivated(1);
                user.setFlatID(user.getId());
                user.setUserType(0);
                itripUserMapper.updateItripUser(user);
                return true;
            }
        }
        return false;
    }

    public void itripCreateUser(ItripUser user) throws Exception{
        itripUserMapper.insertItripUser(user);
    }
}
